package com.hmily.dubbo.provider.sync;

import org.apache.commons.lang3.time.FastDateFormat;

import java.util.Date;

/**
 * <h1>中断案例样例代码。</h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2022-04-10
 */
public class InterruptedExceptionSample {

    public static void main(String[] args) throws Throwable{
        interrupted();
    }

    public static void interrupted() throws Throwable {
        // 模拟服务端执行任务的线程
        final Thread serverTaskThread = new Thread(){
            @Override
            public void run() {
                while(!isInterrupted()) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        System.out.println("serverTaskThread 已经感知到了中断事件~~~, now: " + now());
                        e.printStackTrace();

                        Thread.currentThread().interrupt();
                    }
                }
            }
        };
        // 手动中断服务端任务的线程
        Thread manualInterruptThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("manualInterruptThread 执行中断 serverTaskThread 的请求, now: " + now());
                serverTaskThread.interrupt();
            }
        });
        // 启动 manualInterruptThread 线程，然后等待 1s 后中断 serverTaskThread 线程
        manualInterruptThread.start();
        // 启动 serverTaskThread 线程
        serverTaskThread.start();
        // 等待任务结束
        serverTaskThread.join();
    }


    public static String now() {
        return FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
    }
}
